<?php
/**
 * User:chendenan
 * Created On 2022/3/22 0022 20:37
 */
namespace app\api\controller;
use app\common\lib\Show as ShowLib;
use think\facade\Cache;
use app\common\business\Cart as CartBus;
class Cart extends AuthBase{
    /**
     * 添加购物车
     * @return \think\response\Json
     */
    public function add(){
        if(!$this->request->isPost()){
            return ShowLib::error("非法请求");
        }
        $id = input("param.id",0,"intval");
        $num = input("param.num",0,"intval");
        if(!$id || !$num){
            return ShowLib::error("参数不合法");
        }
        $data = [
            "title" => 'mall',
            "num" => $num,
            "image" => "aaa",
        ];
        $res = (new CartBus())->insertRedis($this->userId,$id,$num);
        if($res===FALSE){
            return ShowLib::error('添加购物车失败');
        }
        return ShowLib::success($res,"购物车添加成功");
    }

    /**
     * 获取购物车列表数据
     * @return \think\response\Json
     */
    public function lists(){
        $ids = input("param.id","","trim");
        $res = (new CartBus())->lists($this->userId,$ids);
        if($res === FALSE){
            return ShowLib::error('获取购物车列表失败');
        }
        return ShowLib::success($res);
    }

    /**
     * 更新购物车商品数量
     * @return \think\response\Json
     */
    public function update(){
        if(!$this->request->isPost()){
            return ShowLib::error('非法请求');
        }
        $id = input("param.id",0,"intval");
        $num = input("param.num",0,"intval");
        if(!$id || !$num){
            return ShowLib::error("参数不合法");
        }
        try{
            $res = (new CartBus())->updateRedis($this->userId,$id,$num);
        } catch (\think\Exception $e){
            return ShowLib::error($e->getMessage());
        }
        if($res === FALSE) {
            return ShowLib::error("购物车更新失败");
        }
        return ShowLib::success($res,"更新成功");
    }

    /**
     * 删除购物车某一商品
     * @return \think\response\Json
     */
    public function delete(){
        if(!$this->request->isPost()){
            return ShowLib::error('非法请求');
        }
//        $id = input("param.id",0,"intval");
//        if(!$id){
//            return ShowLib::error("参数不合法");
//        }
        $id = input("param.id",0,"trim");
        $res = (new CartBus())->deleteRedis($this->userId,$id);
        if($res === FALSE) {
            return ShowLib::error("购物车删除失败");
        }
        return ShowLib::success($res,"删除成功");
    }
}